﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LeetCodeSolutions
{
    /// <summary>
    /// 83. 删除排序链表中的重复元素
    /// </summary>
    class LeetCode83 : LeetCodeBase
    {
        public override void Execute()
        {
            ListNode node4 = new ListNode(3, null);
            ListNode node3 = new ListNode(3, node4);
            ListNode node2 = new ListNode(2, node3);
            ListNode node1 = new ListNode(1, node2);
            ListNode node0 = new ListNode(1, node1);

            DeleteDuplicates(node0);
        }

        public class ListNode
        {
            public int val;
            public ListNode next;
            public ListNode(int val = 0, ListNode next = null)
            {
                this.val = val;
                this.next = next;
            }
        }

        public ListNode DeleteDuplicates(ListNode head)
        {
            if (head == null)
            {
                return null;
            }

            ListNode node = head;

            // 从头开始遍历 保存当前的值
            // 如果下一个值和当前相同 则看下下个
            // 如果下一个值和当前不同 则继续
            int value = node.val;
            while (node != null && node.next != null)
            {
                ListNode nextNode = node.next;
                if (nextNode.val == value)
                {
                    // 相同 则删除
                    node.next = nextNode.next;
                }
                else
                {
                    // 不同 则继续
                    value = nextNode.val;
                    node = nextNode;
                }
            }

            node = head;
            while (node != null)
            {
                CommonFuntions.Print(node.val);
                node = node.next;
            }

            return head;
        }
    }
}
